package com.sasis.webapp.dwr;

import java.util.Collection;
import java.util.Iterator;

import com.sasis.model.Role;
import com.sasis.service.RoleManager;
import com.sasis.service.UserManager;
import com.sasis.util.PageList;
import com.sasis.util.PageRequest;

public class RoleRemote {
	
	private RoleManager roleManager;
	
	private UserManager userManager;
	
	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public PageList searchByName(boolean isRole, String name, int pageIndex) {
		if (isRole) {
			if (name == null || name.trim().length() == 0) {
				return roleManager.findAll(new PageRequest(pageIndex, 10));
			}
			return roleManager.findByLikeName("%" + name.trim() + "%", new PageRequest(pageIndex, 10));
		} else {
			if (name == null || name.trim().length() == 0) {
				return userManager.findAll(new PageRequest(pageIndex, 10));
			}
			return userManager.findByLikeName("%" + name.trim() + "%", new PageRequest(pageIndex, 10));
		}
	}
	
	public String findRolesByUser(String userId) {
		StringBuffer buf = new StringBuffer();
		Collection roles = roleManager.findByUserId(new Long(userId));
		boolean isFirst = true;
		for (Iterator iterator = roles.iterator();iterator.hasNext();) {
			Role role = (Role)iterator.next();
			if (role != null) {
				if (! isFirst) {
					buf.append(",");
				}
				buf.append(role.getName());
			}
			isFirst = false;;
		}
		return buf.toString();
	}

}
